package com.mlnx.device.manager;


import com.mlnx.device.pojo.dto.AutoDetectCmdDto;
import com.mlnx.device.util.SyncFuture;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by amanda.shan on 2019/3/29.
 */
public class XmBpManager {

    public static Map<String, SyncFuture<AutoDetectCmdDto>> syncFutureMap = new
            ConcurrentHashMap<>();

    /**
     * 等待
     * @param autoDetectCmd
     * @return
     * @throws InterruptedException
     */
    public static AutoDetectCmdDto wait(AutoDetectCmdDto autoDetectCmd) throws InterruptedException {

        // 1、清理过期未响应的命令
        for (String key: syncFutureMap.keySet()){

            SyncFuture syncFuture = syncFutureMap.get(key);
            if (System.currentTimeMillis()-syncFuture.getBeginTime() > XmBpManagerConfig.xmbpManagerStaleTime){
                syncFuture.setResponse(null);
                syncFutureMap.remove(key);
            }
        }

        // 等待命令响应
        SyncFuture<AutoDetectCmdDto> syncFuture = new SyncFuture<>();
        syncFutureMap.put(autoDetectCmd.getKey(), syncFuture);

        return syncFuture.get(XmBpManagerConfig.xmbpManagerWaitTime, TimeUnit.SECONDS);
    }

    public static void finishSend(AutoDetectCmdDto autoDetectCmd){
        SyncFuture<AutoDetectCmdDto> autoDetectCmdSyncFuture = syncFutureMap.get(autoDetectCmd.getKey());
        if (autoDetectCmdSyncFuture != null){
            autoDetectCmdSyncFuture.setResponse(autoDetectCmd);
        }

        syncFutureMap.remove(autoDetectCmd.getKey());
    }

}
